#!/usr/bin/python3
# -*- encoding=utf-8 -*-

import requests
import json,time
import user
import resource
import urlparse
import monitor
import sys

reload(sys)

sys.setdefaultencoding('utf-8')


class PostMessage:

    def __init__(self,headers1,headers2,userName,password,metric,valueName,resourceId):  #构造函数
        self.headers1 = headers1  
        self.headers2 = headers2
        self.userName = userName
        self.password = password    
        self.metric = metric
        self.valueName = valueName
        self.resourceId = resourceId

    def postMessage(self):
        session = requests.session()    
        user = user.User(self.headers1,session)
        result = user.login(self.userName,self.password)
        print result
    
        resource = resource.Resource(self.headers1,session)
        res = resource.getResourceById(self.resourceId)
        print res.text
   

        res = res.json()
        endpoint = res['resultData']['paramsMap']['ComputeIP']
        print endpoint

        monitor1 = monitor.Monitor(self.headers1,session)
        res1 = monitor1.getMetricById(self.resourceId)
    #print res1.text 
 
        res = res1.json()
        data = []
        num = 100
        for i in range(res['resultData'][self.metric][0]['metric']):
            if self.valuename in range(res['resultData'][self.metric][0]['metric'][i]):
                num = i
                break
        if num == 100:
            raise Exception('没有这个参数')



        for i in range(len(res['resultData'][self.metric])):
            print i
        
            dict1 = res['resultData'][self.metric][i]['metric'][num]
            print dict1
            times = dict1['time']
            print times
   
            value = dict1['value']
            print value
   
            resourceName = res['resultData'][self.metric][0]['resourceName']
 
            print resourceName

            metric = self.metric + '.' + resourceName + '.' + dict1['name'].replace(" ", "")
            print  metric

            dict2 = {}
    
            dict2["metric"] = str(metric)
            dict2["endpoint"] = str(endpoint) 
            dict2["timestamp"] = int(str(times)[:-3])
            dict2["step"] = 10
            dict2["value"] = float(str(value))
            dict2["tags"] = ""
            dict2["extra"] = "data to collector"
    
            data.append(dict2)

    print  data
    '''
    print  json.dumps(data)
    url = 'http://172.16.32.28:2080/api/collector/push'
    req = requests.post(url,data=json.dumps(data))
    print req

    print req.text    
    '''  

 
